package com.haoyun.common.controller;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.haoyun.common.constant.SecurityConstants;
import com.haoyun.common.core.BaseException;
import com.xiaoleilu.hutool.bean.BeanUtil;
import com.xiaoleilu.hutool.collection.CollectionUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Created by twg on 2018/6/2.
 */
@Slf4j
public class BaseController {
    @Autowired
    private HttpServletRequest request;

    /**
     * 从请求header中的token获取用户角色
     *
     * @return
     */
    protected List<String> findRoles() {
        Enumeration<String> enumeration = request.getHeaders(SecurityConstants.ROLE_HEADER);
        List<String> roles = Lists.newArrayList();
        Iterator<String> iterator = CollectionUtil.asIterator(enumeration);
        if (iterator.hasNext()) {
            roles = Arrays.asList(iterator.next().split(StrUtil.COMMA));
        }
        return roles;
    }

    /**
     * 从请求header中用户信息
     *
     * @return
     */
    protected UserInfo currentUser() {
        String userInfo = request.getHeader(SecurityConstants.USER_INFO_HEADER);
        log.info(" 当前用户信息：{}", userInfo);
        if (StrUtil.isBlank(userInfo)) {
            throw new BaseException("请求头未设置用户信息！");
        }
        Map userMap = (Map) JSON.parse(userInfo);
        return BeanUtil.mapToBean(userMap, UserInfo.class, true);
    }
}
